<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:announcement:save']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:announcement:update']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['sys:announcement:delete']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="announcementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="10" align="center" />
      <el-table-column label="" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="发布人" align="center" prop="sender" />
      <el-table-column label="优先级" align="center" prop="priorityDesc" />
      <el-table-column label="消息类型" align="center" prop="msgCategoryDesc" />
      <el-table-column label="通知范围" align="center" prop="msgTypeDesc" />
      <el-table-column label="发布状态" align="center" prop="sendStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sendStatus=='1'">
            未发布
          </el-tag>
          <el-tag v-else-if="scope.row.sendStatus=='2'" type="success">
            已发布
          </el-tag>
          <el-tag v-else type="danger">
            已撤销
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="sendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sendTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="撤销时间" align="center" prop="cancelTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cancelTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="摘要" align="center" prop="msgAbstract" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['sys:announcement:update']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            v-hasPermi="['sys:announcement:delete']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-hasPermi="['sys:announcement:release']" icon="el-icon-s-promotion" @click.native="handleRelease(scope.row)">
                发布
              </el-dropdown-item>
              <el-dropdown-item v-hasPermi="['sys:announcement:revoke']" icon="el-icon-refresh-left"
                                @click.native="handleRevoke(scope.row)"
              >
                撤销
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-view"
                                @click.native="handleView(scope.row)"
              >
                查看
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改系统通告对话框 -->
    <el-dialog v-if="open" :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" clearable
                          size="small"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" clearable
                          size="small"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="选择结束时间"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择消息优先级">
            <el-option label="低" :value="'L'" />
            <el-option label="中" :value="'M'" />
            <el-option label="高" :value="'H'" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息类型" prop="msgCategory">
          <el-select v-model="form.msgCategory" placeholder="请选择消息类型">
            <el-option label="通知公告" :value="'1'" />
            <el-option label="系统消息" :value="'2'" />
          </el-select>
        </el-form-item>
        <el-form-item label="通知范围" prop="msgType">
          <el-select v-model="form.msgType" placeholder="请选择通知对象类型">
            <el-option label="指定用户" :value="'1'" />
            <el-option label="全部用户" :value="'2'" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.msgType==1" label="指定用户" prop="userIdList">
          <el-select
            v-model="form.userIdList"
            class="width-full"
            multiple placeholder="请选择用户"
            @remove-tag="handleRemoveUserTag"
            @click.native="handleOpenUserTable"
          >
            <el-option
              v-for="item in form.userSelectList"
              :key="item.id"
              :disabled="true"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="摘要" prop="msgAbstract">
          <el-input v-model="form.msgAbstract" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="内容" prop="msgContent">
          <Tinymce v-model="form.msgContent" :height="192" placeholder="在这里输入文字" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">
          确 定
        </el-button>
        <el-button @click="cancel">
          取 消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="showOpen" title="通知详情" :visible.sync="showOpen" width="800px" append-to-body>
      <iframe :src="showDetailUrl" class="detail-iframe" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="showOpen=false">
          取 消
        </el-button>
      </div>
    </el-dialog>
    <user-choose-table ref="userChooseTable" v-model="form.userSelectList" @submit="handleUserTableSubmit" />
  </div>
</template>

<script>
import {
  addAnnouncement,
  delAnnouncement,
  getAnnouncement,
  listAnnouncement,
  releaseAnnouncement,
  revokeAnnouncement,
  updateAnnouncement
} from "@/api/system/announcement.js"
import UserChooseTable from '@/views/system/user/chooseTable'
import {listUser} from "../../../api/system/user"
import {getTokenUrl} from "../../../utils/auth"

export default {
  name: "Announcement",
  components: {
    UserChooseTable
  },
  data() {
    let validateEndTime = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请选择结束时间"))
      } else {
        if (!this.form.startTime) {
          callback(new Error("请选择开始时间！"))
        } else if (Date.parse(this.form.startTime) >= Date.parse(value)) {
          callback(new Error("结束时间必须大于开始时间！"))
        } else {
          callback()
        }
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系统通告表格数据
      announcementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showOpen: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        title: null
      },
      showDetailUrl: '',
      // 问卷参数
      form: {
        priority: "L",
        msgCategory: "1",
        msgType: "1",
        userIdList: [],
        userSelectList: []
      },
      // 问卷校验
      rules: {
        msgCategory: [
          {required: true, message: "消息类型不能为空", trigger: "blur"}
        ],
        title: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        endTime: [
          {required: true, message: "结束时间不能为空", trigger: "blur"},
          {required: true, validator: validateEndTime, trigger: "blur"}
        ],
        startTime: [
          {required: true, message: "开始时间不能为空", trigger: "blur"}
        ],
        msgType: [
          {required: true, message: "通知范围不能为空", trigger: "blur"}
        ],
        noticeContent: [
          {required: true, message: "通知范围不能为空", trigger: "blur"}
        ],
        userIdList: [
          {required: true, message: "请选择通知用户", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询系统通告列表 */
    getList() {
      this.loading = true
      listAnnouncement(this.queryParams).then((response) => {
        this.announcementList = response.data.records
        this.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 问卷重置
    reset() {
      this.form = {
        id: null,
        title: null,
        msgContent: null,
        startTime: null,
        endTime: null,
        priority: "L",
        msgCategory: "1",
        msgType: "1",
        sendTime: null,
        userIds: null,
        msgAbstract: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加系统通告"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getAnnouncement(id).then((response) => {
        this.form = response.data
        listUser({userIds: response.data.userIds}).then((res) => {
          this.form.userSelectList = res.data
          this.form.userIdList = res.data.map((item) => item.id)
        })
        this.open = true
        this.title = "修改系统通告"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.userIds = this.form.userIdList.join(",")
          if (this.form.id != null) {
            updateAnnouncement(this.form).then((response) => {
              this.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAnnouncement(this.form).then((response) => {
              this.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除系统通告编号为"' + ids + '"的数据项？').then(function () {
        return delAnnouncement(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    handleUserTableSubmit(val) {
      this.form.userSelectList = val
      this.form.userIdList = val.map((item) => item.id)
    },
    handleRemoveUserTag(val) {
      this.form.userSelectList = this.form.userSelectList.filter((item) => item.id !== val)
    },
    handleOpenUserTable() {
      this.$refs.userChooseTable.showDialog(this.form.userSelectList?this.form.userSelectList:[])
    },
    handleRelease(row) {
      this.$confirm('是否确认发布系统通告"' + row.title + '"？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return releaseAnnouncement(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess("发布成功")
      }).catch(() => {
      })
    },
    handleView(row) {
      this.showOpen = true
      console.log(row)
      this.showDetailUrl = getTokenUrl('/sys/announce/show/' + row.id)
    },
    handleRevoke(row) {
      this.$confirm('是否确认撤回系统通告"' + row.title + '"？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return revokeAnnouncement(row.id)
      }).then(() => {
        this.getList()
        this.msgSuccess("撤回成功")
      }).catch(() => {
      })
    }
  }
}
</script>
<style>
.detail-iframe {
  border: 0;
  width: 100%;
  //height: 88vh;
  min-height: 600px;
}
</style>
